package main

import (
	"errors"
	"fmt"
	"modbus-tools/utils/tools"
	"strings"
)

func Uint16BitsToUint8(data uint16, startBit, endBit int, endian string) (value uint8, err error) {
	if startBit > endBit {
		err = errors.New("开始位大于结束位")
		return
	}
	str := tools.Uint16ToBinaryString(data)
	fmt.Printf("str --- %s\n", str)
	str = tools.StringReverse(str)
	part := tools.SubStr(str, startBit, endBit-startBit+1)
	part = tools.StringReverse(part)
	fmt.Printf("part--- %s\n", part)
	if len(part) > 8 {
		err = errors.New("位长度超出8位")
		return
	}
	if len(part) < 8 {
		part = strings.Repeat("0", 8-len(part)) + part
	}
	value, err = tools.BinaryStringToByte(part)
	return
}

func main() {
	n1 := uint16(257*2 + 257)
	value, err := Uint16BitsToUint8(n1, 8, 12, "big")
	fmt.Printf("value=%d, err=%v\n", value, err)
}
